package com.fly.dynsql;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fly.common.util.NamedSqlExecutor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class DynTestCase
{
    @Autowired
    private NamedSqlExecutor namedSqlExecutor;
    
    @Autowired
    private SqlXmlUtil sqlXmlUtil;
    
    public void run()
    {
        // 传入动态参数, 可不传或传入空值
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("id", defaultOrNull(1));
        params.put("name", defaultOrNull("name%"));
        params.put("maxId", defaultOrNull(100));
        params.put("ids", defaultOrNull(Arrays.asList(1, 2, 3)));
        log.info("★★★★ input : params = {}", params);
        
        // 处理后的动态SQL相关信息
        String namedParamSql = sqlXmlUtil.getSqlById("demo.sql001", params);
        log.info("★★★★ processed: params = {}", params);
        log.info("★★★★ processed: namedParamSQL  = {}", namedParamSql);
        
        // 执行数据查询操作
        List<Map<String, Object>> list = namedSqlExecutor.queryForList(namedParamSql, params);
        log.info("★★★★ execute: result   = {}", list);
    }
    
    /**
     * 返回默认值或者空值
     * 
     * @param defaultValue
     * @return
     * @see [类、类#方法、类#成员]
     */
    private Object defaultOrNull(Object defaultValue)
    {
        if (RandomUtils.nextBoolean())
        {
            return defaultValue;
        }
        // 返回空值处理
        if (String.class.isInstance(defaultValue))
        {
            // 字符串, null 或 "" 视为空值
            return RandomUtils.nextBoolean() ? null : "";
        }
        if (List.class.isInstance(defaultValue))
        {
            // List对象, null或 emptyList视为空值
            return RandomUtils.nextBoolean() ? null : Collections.emptyList();
        }
        return null;
    }
}
